// import * as echarts from 'echarts'
import { useEffect, useState } from 'react'
import axios from '@/http'
import { TBlog } from '@type'
import { getCurrentMonthList, getLastYearDate, getNextYearDate } from './util'
import { formatYMTime } from '@/util'
import './writeChart.scss'
import { Button } from 'antd'
import * as echarts from 'echarts/core'
import { GridComponent, TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import { LineChart, PieChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([GridComponent, PieChart, LineChart, CanvasRenderer, UniversalTransition, TitleComponent, TooltipComponent, LegendComponent])
type TChartWrite = {
  allCount: number[]
}
type TPieDate = {
  value: number
  name: string
}
const WriteChart = () => {
  const [chartType, setChartType] = useState('line')
  const [option, setOption] = useState({})
  const [currentDate, setCurrentDate] = useState('')
  const handleData = (currentDate: string | Date, writeData: number[]) => {
    setOption({
      title: {
        text: '写作数量折线图'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['总数']
      },
      xAxis: {
        type: 'category',
        data: getCurrentMonthList(currentDate)
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          label: {
            show: true,
            position: 'top'
          },
          name: '总数',
          data: writeData,
          type: 'line'
        }
      ]
    })
  }
  const [pieData, setpieData] = useState<TPieDate[]>([])
  const handlePieData = (blogData: TBlog[]) => {
    if (pieData.length === 0) {
      const temPieData: TPieDate[] = []
      blogData.forEach(item => {
        const findData = temPieData.find(items => item.way === items.name)
        findData ? findData.value++ : temPieData.push({ name: item.way, value: 1 })
      })
      setpieData(temPieData)
    } else {
      setpieData(pieData)
    }
  }
  const [allDate, setallDate] = useState<TBlog[]>([])
  const getBlogList = () => {
    axios.get('/blog/alllist').then(res => {
      if (res.data.error === -1) {
        const data: TBlog[] = res.data.data
        setallDate(data)
        changeDate(data)
        handlePieData(data)
      }
    })
  }
  const goLastYear = () => {
    const lastYearDate = getLastYearDate(currentDate)
    setCurrentDate(lastYearDate)
    changeDate(allDate, lastYearDate)
  }
  const goNextYear = () => {
    const nextYearDate = getNextYearDate(currentDate)
    setCurrentDate(nextYearDate)
    changeDate(allDate, nextYearDate)
  }
  const changeDate = (data: TBlog[], date: string | Date = new Date()) => {
    const blogCount: TChartWrite = { allCount: [] }
    blogCount.allCount.length = 12
    blogCount.allCount.fill(0)
    data.forEach(item => {
      const index = getCurrentMonthList(date).findIndex(items => items === formatYMTime(item.time))
      index !== -1 && (blogCount.allCount[index] += 1)
    })
    handleData(date, blogCount.allCount)
  }
  const [myChart, setmyChart] = useState<any>()
  useEffect(() => {
    var chartDom = document.getElementById('main')
    var myChart = chartDom && echarts.init(chartDom)
    const date = new Date()
    setCurrentDate(`${date.getFullYear()}-${date.getMonth() + 1}`)
    setmyChart(myChart)
    getBlogList()
  }, [])
  useEffect(() => {
    myChart && myChart.setOption(option, true)
  }, [option])
  const showPie = () => {
    setOption({
      title: {
        text: '博客分类数据图',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '类型分布',
          type: 'pie',
          radius: '50%',
          data: pieData,
          label: {
            alignTo: 'edge',
            formatter: '{name|{b}}: {time|{c}} 篇',
            minMargin: 5,
            lineHeight: 20,
            rich: {
              time: {
                fontSize: 10,
                color: '#999'
              }
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
    setChartType('pie')
  }
  const showLine = () => {
    changeDate(allDate)
    setChartType('line')
  }
  return (
    <>
      <div id="main"></div>
      <div style={{ textAlign: 'center' }}>
        {chartType === 'line' ? (
          <>
            <Button onClick={goLastYear}>上一年</Button>
            <Button onClick={goNextYear} style={{ marginLeft: '36px' }}>
              下一年
            </Button>
            <Button onClick={showPie} style={{ marginLeft: '36px' }}>
              展示饼状图
            </Button>
          </>
        ) : (
          <>
            <Button onClick={showLine} style={{ marginLeft: '36px' }}>
              展示折线图
            </Button>
          </>
        )}
      </div>
    </>
  )
}
export default WriteChart
